import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/hj_model/message/search_user_obj.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:tiktokadult/tools_base/ad_insert_manager.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';

import '../../../hj_model/home/home_tabs_entity.dart';
import '../../main_page/provider/bottom_bar_provider.dart';

class CommunityTabLogic extends GetxController {
  final ModuleData? model;
  final int index;

  CommunityTabLogic(this.model, {this.index = 0});

  RefreshController? refreshController;
  late ScrollController sctrl = ScrollController();

  int page = 1;
  bool isLoading = true;

  /// 索引
  int sort = 0;
  RxBool sortMenuIsTop = false.obs;
  List<String> titleArr = ["推荐", "最新", "最热", "精华", '视频'];
  List<VideoModel> dataSource = [];

  /// 顶部的专题
  final specials = [];
  static List<HotBloggerEntity>? hotUpList;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    CommunityBottomProvider().setSrollController(index, controller: sctrl);
    fetchPagedata();
  }

  Future loadHotUpUser() async {
    if (hotUpList == null) {
      try {
        var resp = await VidService.fetchUpList(1, 24);
        hotUpList = resp?.list ?? [];
      } catch (e) {
        debugLog(e);
      }
    }
  }

  void scrollerToTop() {
    sctrl.jumpTo(0);
  }

  fetchPagedata({bool isRefresh = true, bool needLoading = false}) async {
    await loadHotUpUser();
    if (isRefresh) {
      page = 1;
    }
    if (needLoading) {
      isLoading = true;
      update();
    }
    final res = await VidService.getModuleDetail(model?.id ?? '', pageNumber: page, moduleSort: [7, 1, 3, 2, 6][sort]);
    isLoading = false;
    if (isRefresh) {
      dataSource.clear();
      refreshController?.refreshCompleted();
    }
    if (res?.hasNext ?? false) {
      refreshController?.loadComplete();
    } else {
      refreshController?.loadNoData();
    }
    dataSource.addAll(res?.allVideoInfo ?? []);
    if ((res?.allSection?.isNotEmpty ?? false) && specials.isEmpty) {
      specials.addAll(res!.allSection?.firstOrNull?.allTags ?? []);
    }
    AdInsertManager.postUpUser(dataSource, hotUpList ?? []);
    page += 1;
    update();
  }
}
